<template>
  <div class="login-bg">
    <el-card class="login-card">
      <h2>登录</h2>
      <el-form :model="form" @submit.prevent="onLogin">
        <el-form-item label="用户名">
          <el-input v-model="form.username" autocomplete="username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" autocomplete="current-password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin">登录</el-button>
          <el-button @click="goRegister" type="text">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/auth'

const router = useRouter()
const form = ref({ username: '', password: '' })

const onLogin = async () => {
  try {
    const params = new URLSearchParams(form.value)
    const res = await login(params)
    // 保存token
    localStorage.setItem('token', res.data.access_token)
    // 保存用户名
    localStorage.setItem('username', form.value.username)
    // 跳转首页
    router.push('/')
  } catch (e) {
    alert(e.response?.data?.detail || '登录失败')
  }
}

const goRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
    url('https://ts1.tc.mm.bing.net/th/id/R-C.2fc875e6db412ea3001859644782e86c?rik=OXSZZhqD4QszEg&riu=http%3a%2f%2fpic30.photophoto.cn%2f20140324%2f0034034401728510_b.jpg&ehk=Q46dXLrEabrJDvvcvRaoVNz036jAfl4H0B2d0g%2fQZmA%3d&risl=&pid=ImgRaw&r=0');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-card {
  width: 400px;
  padding: 40px;
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
}

h2 {
  text-align: center;
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 30px;
  font-weight: 600;
  letter-spacing: 1px;
}

:deep(.el-form-item__label) {
  color: #606266 !important;
  font-weight: 500;
  width: 80px; /* 设置固定宽度，可根据实际情况调整 */
  text-align: right; /* 使标签文本右对齐，看起来更整齐 */
}
:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 12px 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  width: calc(100% - 80px - 20px); /* 确保输入框宽度与标签配合，20px是间距，可调整 */
  display: inline-block; /* 使输入框和标签在同一行 */
}
:deep(.el-button) {
  border-radius: 8px;
  padding: 12px 24px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  transform: translateY(-2px);
}

:deep(.el-button--text) {
  color: #606266;
}

:deep(.el-button--text:hover) {
  color: #409eff;
}
</style>